package com.bonc.datasource;//package com.bonc.core.datasource;
//
//import com.alibaba.druid.pool.DruidDataSource;
//import com.bonc.core.entity.xhzc.DmCxqDatabase;
//import com.bonc.industry.core.spring.ApplicationContextProvider;
//import com.bonc.web.service.xhzc.IDmCxqDatabaseService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Configuration;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * 初始化动态数据源
// * @author guomh
// * @date 2019/11/06
// */
//@Slf4j
//@Configuration
//public class DynamicDataSourceInit {
//
//    @Resource
//    private IDmCxqDatabaseService dmCxqDatabaseService;
//
//    @Autowired
//    private ApplicationContextProvider applicationContextProvider;
//
//    @PostConstruct
//    public void InitDataSource()  {
//        log.info("=====初始化动态数据源=====");
//        DynamicDataSource dynamicDataSource = (DynamicDataSource)applicationContextProvider.getBean("dynamicDataSource");
//        DruidDataSource defaultDataSource = (DruidDataSource)applicationContextProvider.getBean("defaultDataSource");
//        Map<Object, Object> dataSourceMap = new HashMap<>();
//        dataSourceMap.put("default", defaultDataSource);
//
//        List<DmCxqDatabase> dmCxqDatabaseList = dmCxqDatabaseService.getDmCxqDatabase();
//        for (DmCxqDatabase dmCxqDatabase : dmCxqDatabaseList) {
//            log.info(dmCxqDatabase.toString());
//            DruidDataSource dataSource = new DruidDataSource();
//            dataSource.setDriverClassName(dmCxqDatabase.getDriverClassName());
//            dataSource.setUrl(dmCxqDatabase.getUrl());
//            dataSource.setUsername(dmCxqDatabase.getUserName());
//            dataSource.setPassword(dmCxqDatabase.getUserPassword());
//            dataSourceMap.put(dmCxqDatabase.getDatabaseId(), dataSource);
//        }
//        //设置数据源
//        dynamicDataSource.setTargetDataSources(dataSourceMap);
//        /**
//         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
//         */
//        dynamicDataSource.afterPropertiesSet();
//    }
//
//}
